package com.itheima.health.utils;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

@Data
@AllArgsConstructor
@Slf4j
public class AliMessageUtil {
    private String accessKeyId;
    private String accessKeySecret;
    private String messageEndpoint;//dysmsapi.aliyuncs.com
    private String signName;
    private String templateCode;
//    private String templateParam;
//    private String phoneNumbers;


    /**
     * 初始化阿里Client对象
     *
     * @throws Exception
     */
    private Client createClient() throws Exception {
               Config config = new Config()
                .setAccessKeyId(accessKeyId)
                .setAccessKeySecret(accessKeySecret);
        config.endpoint = messageEndpoint;
        return new Client(config);
    }

    /**
     * 发送短信
     * @param phoneNumbers
     * @param templateParam
     * @throws Exception
     */
    public void sentMessage(String phoneNumbers,String templateParam) throws Exception {
        Client client = createClient();
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setSignName(signName)
                .setTemplateCode(templateCode)
                .setPhoneNumbers(phoneNumbers)
                // TODO 固定的模板类型，code应该改为入参动态的类型
                .setTemplateParam("{\"code\":\""+templateParam+"\"}");

        RuntimeOptions runtimeOptions = new RuntimeOptions();
        try {
            SendSmsResponse sendSmsResponse = client.sendSmsWithOptions(sendSmsRequest, runtimeOptions);
            System.out.println("sendSmsResponse.message = " + sendSmsResponse.getBody().message);
        }catch (TeaException error){
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }

    }
}
